import React, { useState, useEffect, useContext } from 'react';
import CommentForm from './CommentForm';
import CommentList from './CommentList';
import { AuthContext } from '../../contexts/AuthContext';
import api from '../../services/api';

const CommentSection = ({ articleId }) => {
  const { user } = useContext(AuthContext);
  const [comments, setComments] = useState([]);
  const [isLoading, setIsLoading] = useState(true);
  const [error, setError] = useState(null);

  useEffect(() => {
    if (articleId) {
      fetchComments();
    }
  }, [articleId]);

  const fetchComments = async () => {
    setIsLoading(true);
    setError(null);
    try {
      const response = await api.get(`/api/articles/${articleId}/comments`);
      // 将评论数据转换为嵌套结构，以便于渲染树形评论
      const processedComments = processCommentsIntoTree(response.data);
      setComments(processedComments);
    } catch (err) {
      console.error('Failed to fetch comments:', err);
      setError('获取评论失败');
    } finally {
      setIsLoading(false);
    }
  };

  // 将平面结构的评论数据转换为树形结构
  const processCommentsIntoTree = (commentsData) => {
    const commentMap = {};
    const rootComments = [];

    // 首先建立每个评论的映射
    commentsData.forEach(comment => {
      comment.replies = [];
      commentMap[comment.id] = comment;
    });

    // 然后构建评论树
    commentsData.forEach(comment => {
      if (comment.parentId) {
        // 如果有父评论，添加到父评论的回复列表中
        const parent = commentMap[comment.parentId];
        if (parent) {
          parent.replies.push(comment);
        } else {
          // 父评论不存在，作为顶级评论处理
          rootComments.push(comment);
        }
      } else {
        // 顶级评论
        rootComments.push(comment);
      }
    });

    return rootComments;
  };

  const handleCommentSubmit = async (data) => {
    try {
      const response = await api.post(`/api/articles/${articleId}/comments`, {
        ...data,
        articleId
      });
      fetchComments(); // 重新获取所有评论以更新界面
      return true;
    } catch (err) {
      console.error('Failed to submit comment:', err);
      return false;
    }
  };

  const handleReply = async (parentId, data) => {
    try {
      const response = await api.post(`/api/articles/${articleId}/comments`, {
        ...data,
        articleId,
        parentId
      });
      fetchComments(); // 重新获取所有评论以更新界面
      return true;
    } catch (err) {
      console.error('Failed to submit reply:', err);
      return false;
    }
  };

  const handleLike = async (commentId) => {
    try {
      const response = await api.post(`/api/comments/${commentId}/like`);
      fetchComments(); // 重新获取所有评论以更新界面
      return true;
    } catch (err) {
      console.error('Failed to like comment:', err);
      return false;
    }
  };

  const handleDelete = async (commentId) => {
    if (!window.confirm('确定要删除此评论吗？')) {
      return false;
    }
    
    try {
      await api.delete(`/api/comments/${commentId}`);
      fetchComments(); // 重新获取所有评论以更新界面
      return true;
    } catch (err) {
      console.error('Failed to delete comment:', err);
      return false;
    }
  };

  return (
    <div className="comment-section bg-white dark:bg-dark-900 rounded-lg shadow-sm p-6 mt-8">
      <h2 className="text-xl font-bold mb-6 text-gray-900 dark:text-white">评论 ({comments.length})</h2>
      
      <CommentForm onSubmit={handleCommentSubmit} />
      
      <div className="mt-8">
        <CommentList 
          comments={comments}
          onReply={handleReply}
          onLike={handleLike}
          onDelete={handleDelete}
          isLoading={isLoading}
          error={error}
        />
      </div>
    </div>
  );
};

export default CommentSection; 